/*
 * @description: 
 * @Author: Islands
 * @Date: 2023-04-20 15:47:45
 * @LastEditTime: 2024-03-25 20:18:23
 */
import axios from "axios";
export const request = (config: any) => {
    const instance = axios.create({
        baseURL: '/api',
        timeout: 5000,
        headers: {
            "Content-Type": "multipart/form-data",
        }
    });

    //2.请求拦截器
    instance.interceptors.request.use(function (config: any) {
        const accessToken = localStorage.getItem("accessToken");
        if (accessToken) {
            config.headers.Authorization = accessToken;
        }
        return config;
    }, function (error) {
        return Promise.reject(error);
    });

    //3.响应拦截器->获取后台数据前拦截
    instance.interceptors.response.use(function (response) {
        const { status } = response;
        return response.data;
    }, function (error) {
        const { response } = error;
        return response;
    })
    //发送一个真实的请求
    return instance(config);
}



// 封装 GET POST 请求并导出
export function axiosRequest(url = '', params = {}, type = 'POST') {
    //设置 url params type 的默认值
    return new Promise((resolve, reject) => {
        let promise: any
        if (type.toUpperCase() === 'GET') {
            promise = request({
                url,
                params
            })
        } else if (type.toUpperCase() === 'POST') {
            promise = request({
                method: 'POST',
                url,
                data: params
            })
        }
        //处理返回
        promise.then((res: any) => {
            resolve(res)
        }).catch((err: any) => {
            reject(err)
        })
    })
}
